package com.zf.zffencheng.util.api.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.william.yun.yunliwuli.api.HttpResponse;
import com.william.yun.yunliwuli.api.request.binding.PubBindUpdateRequest;
import com.william.yun.yunliwuli.api.request.gateway.AddGatewayRequest;
import com.william.yun.yunliwuli.api.request.goods.Goods;
import com.william.yun.yunliwuli.api.request.goods.GoodsRequest;
import com.william.yun.yunliwuli.api.request.label.Macs;
import com.william.yun.yunliwuli.api.request.label.PubLabelBindingRequest;
import com.william.yun.yunliwuli.api.request.login.LoginRequest;
import com.william.yun.yunliwuli.api.request.store.StoreRequest;
import com.william.yun.yunliwuli.api.response.label.PubLabelBindingAddResponse;
import com.william.yun.yunliwuli.api.response.login.LoginOkResponse;
import com.william.yun.yunliwuli.api.rest.*;
import com.william.yun.yunliwuli.constant.YunliwuliConstant;
import com.zf.zffencheng.dao.HardwarePartnerAccountDao;
import com.zf.zffencheng.exception.ResultException;
import com.zf.zffencheng.model.pojo.HardwarePartnerAccount;
import com.zf.zffencheng.util.api.YunliWuliService;
import lombok.extern.log4j.Log4j2;

import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Log4j2
public class YunliWuliLoginServiceImpl implements YunliWuliService {
	@Autowired
	private HardwarePartnerAccountDao hardwarePartnerAccountDao;
	@Autowired
	private RedissonClient redissonClient;

	@Override
	public String login(Integer accountId) {
		String key = REDIS_TOKEN_KEY + accountId;
		RBucket<String> bucket = redissonClient.getBucket(key, StringCodec.INSTANCE);
		String token =  bucket.get();
		if (ObjectUtils.isEmpty(token)) {
			HardwarePartnerAccount hardwarePartnerAccount = hardwarePartnerAccountDao.selectById(accountId);
			LoginRequest loginRequest = new LoginRequest(hardwarePartnerAccount.getLoginName(),
					hardwarePartnerAccount.getPassword());
			log.info("LoginOkResponse{}", JSON.toJSON(loginRequest));
			LoginOkResponse login = new LoginApi().login(loginRequest);
			log.info("LoginOkResponse{}", JSON.toJSON(login));
			if (login.getErrcode() == null) {
				log.info("授权失败");
				throw new ResultException(500, "硬件系统授权失败");
			}
			if (login.getErrcode() == 200) {
				token = YunliwuliConstant.TOKEN_PREFIX.concat(login.getBody().getToken());
				bucket.set(token, TOKEN_EXPIRE, TimeUnit.SECONDS);
			}
		}
		return token;
	}

	@Override
	public HttpResponse addStore(StoreRequest storeRequest, String login) {
		HttpResponse r = new StoreApi().addStore(storeRequest, login);
		return r;
	}

	@Override
	public HttpResponse addGateway(AddGatewayRequest request, String login) {
		HttpResponse r = new GatewayApi().addGateway(request, login);
		return r;
	}

	@Override
	public HttpResponse addLabelAndBinding(String deviceSn, String secretKkey, String storeUUID, String token) {
		// 添加价签
		PubLabelBindingRequest pubLabelBindingRequest = new PubLabelBindingRequest();
		List<Macs> macs = new ArrayList<>();
		Macs mac = new Macs();
		mac.setMac(deviceSn);
		mac.setActivekey(secretKkey);
		macs.add(mac);
		pubLabelBindingRequest.setMacs(macs);
		pubLabelBindingRequest.setStoreUuid(storeUUID);
		LabelApi labelApi = new LabelApi();
		String req = JSON.toJSONString(pubLabelBindingRequest);
		log.info(req);
		JSONObject jSONObject = JSONObject.parseObject(req);
		JSONArray jsonArray = jSONObject.getJSONArray("macs");
		log.info("jsonArray{}", jsonArray);
		PubLabelBindingAddResponse pubLabelBindingAddResponse = labelApi.pubLabelAdd(pubLabelBindingRequest, token);
		Integer status = pubLabelBindingAddResponse.getStatus();
		if (status != 200) {
			throw new ResultException(status, pubLabelBindingAddResponse.getMsg());
		}
		// 绑定价签至网关
		HttpResponse r = labelApi.pubLabelBinding(pubLabelBindingRequest, token);
		if (r.getStatus() != 200) {
			if (r.getStatus() == 405) {
				throw new ResultException(r.getStatus(), "MAC添加异常");
			}
			throw new ResultException(r.getStatus(), r.getMsg());
		}
		return r;
	}

	@Override
	public Goods addGoods(String uuid, String storeUUID, String token, String label4, String label5) {
		List<Goods> list = new ArrayList<>();
		Goods goods1 = new Goods();
		goods1.setBarcode(uuid);
		goods1.setQrcode("");
		goods1.setLabel1("");
		goods1.setLabel2("");
		goods1.setLabel3("");
		goods1.setLabel4(StringUtils.hasLength(label4) ? label4 :"被供奉人");
		goods1.setLabel5(StringUtils.hasLength(label5) ? label5 :"供奉位置");
		goods1.setLabel7("牌位");
		goods1.setLabel8("供奉人");

		list.add(goods1);
		GoodsRequest goodsRequest = new GoodsRequest(list, storeUUID);
		HttpResponse httpResponse = new GoodsApi().addGoods(goodsRequest, token);
		if (httpResponse.getStatus() != 200) {
			throw new ResultException(500, httpResponse.getMsg());
		}

		return goods1;
	}

	@Override
	public HttpResponse updatebinding(String deviceSn, String templateNo, String storeUUID, String token) {
		PubBindUpdateRequest pubBindUpdateRequest = new PubBindUpdateRequest();
		pubBindUpdateRequest.setMac(deviceSn);
		pubBindUpdateRequest.setDemoId(templateNo);
		pubBindUpdateRequest.setStoreUuid(storeUUID);
		pubBindUpdateRequest.setBarcode(deviceSn);
		log.info("pubBindUpdateRequest{}", JSON.toJSONString(pubBindUpdateRequest));
		HttpResponse httpResponse = new BindingApi().pubBindUpdate(pubBindUpdateRequest, token);
		/*
		 * if (httpResponse.getStatus() != 200) { throw new BusinessException(500,
		 * httpResponse.getMsg()); }
		 */
		log.info("httpResponse{}", JSON.toJSONString(httpResponse));
		return httpResponse;
	}

}
